import random
from fastapi import FastAPI
import sqlite3
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware

app=FastAPI()
#TODO部署到服务器

origins = [
    "https://codeful.cn.eo.dnse2.com",
    "http://codeful.cn.eo.dnse2.com",
    "http://localhost",
    "http://localhost:5173",
    
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 
devMode=True
#初始化fastapi

class Leaderboard(BaseModel):
    name:str
    score:int
    clicks:int


#连接数据库，创建cursor
get_dbconn=sqlite3.connect("fastapi_leaderboard.db")
# 生成测试数据
generate_test_data=lambda n:[(f'test{i}',random.randint(1,100),random.randint(40,500)) for i in range(n)]
test_data=generate_test_data(20)

with get_dbconn as conn:

    cursor=conn.cursor()
    #创建表
    cursor.execute('''  CREATE TABLE IF NOT EXISTS leaderboard (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        score INTEGER NOT NULL,
        clicks INTEGER NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
        )'''
    )
    #插入测试数据
    cursor.executemany("INSERT INTO leaderboard (name,score,clicks) VALUES (?,?,?)",test_data)


# 获取总记录数
@app.get("/api/leaderboard/total")
async def get_total_number():
    with get_dbconn as conn:
        cursor=conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM leaderboard")
        total_number=cursor.fetchall()
        return {"total_number":total_number}



@app.get("/api/leaderboard")
async def get_leaderboard():
    """_summary_
    获取排行榜数据库前10名

    Returns:
        _type_: _description_
    """ 
    with get_dbconn as conn:
        cursor=conn.cursor()
        cursor.execute("SELECT * FROM leaderboard ORDER BY score DESC LIMIT 10")
        rows=cursor.fetchall()
        return rows

@app.post("/api/leaderboard")
async def post_leaderboard(item:Leaderboard):
    """推送新分数到排行榜数据库

    Args:
        item (Leaderboard): 排行榜一行的数据

    Returns:
        json: 成功消息
    """
    with get_dbconn as conn:
        cursor=conn.cursor()
        
        cursor.execute("INSERT INTO leaderboard (name,score,clicks) VALUES (?,?,?)",(item.name,item.score,item.clicks))
        conn.commit()
        return {"message":"Score posted successfully"}


# TODO:引入中间件进行跨域控制
# 
# :输入校验/上下文控制（with）
# TODO:在网页上测试post接口

#TODO:服务器运行在https上,不然会报错



#使用装饰器管理数据库操作，自动处理游标和数据库连接的打开关闭。
#TODO:还没写完继续写
def db_action(func):
    def wrapper(*args,**kwargs):
        #使用上下文管理器
        with get_dbconn as conn:
            
            result=func(*args,**kwargs)
            conn.commit()
            return result
    return wrapper

@db_action
def write_score(name,score,clicks):
    try:
        cursor.execute("INSERT INTO leaderboard (name,score,clicks) VALUES (?,?,?)",(name,score,clicks))
    except Exception as e:
        print(e)
    return {"message":"Score posted successfully"}

#测试行


